
package com.zany.util.date;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.log4j.Logger;


public class DateFormater {
	
	private static Logger logger = Logger.getLogger(DateFormater.class);
	private static final String[] NUMBERS = { "零", "壹", "贰", "叁", "肆", "伍",
        "陆", "柒", "捌", "玖" };
	/**
	 * 格式化日期 为 yyyy/MM/dd 的样式
	 * 
	 * @param date
	 * @return
	 */
	public static String formatDate(Date date) {
	    return formatDate(date, DateFormatPattern.DEFAULT_FULL_DATE);
	}
	/**
	 * 格式化日期 为 yyyy/MM/dd HH:mm:ss的样式
	 * 
	 * @param date
	 * @return
	 */
	public static String getStrTimestamp(Date date) {
	    return formatDate(date, DateFormatPattern.DEFAULT_FULL_TIMESTAMP);
	}
	
	public static String getTimeForOrderId(Date date){
		return formatDate(date, DateFormatPattern.DEFAULT_FULL_TIMESTAMP_NO_PARTITION);
	}
	/**
	 * 將系統當前格式化日期 为 yyyy/MM/dd 的样式
	 * 
	 * @param date
	 * @return
	 */
	public static String getSystemCurrentDate() {
		return formatDate(Calendar.getInstance().getTime(), DateFormatPattern.DEFAULT_FULL_DATE);
	}
	
	/**
	 * 將系統當前格式化日期 为 yyyyMMdd 的样式
	 * 
	 * @param date
	 * @return
	 */
	public static String getSystemCurrentDateSimple() {
		return formatDate(Calendar.getInstance().getTime(), DateFormatPattern.DEFAULT_FULL_DATE_NO_PARTITION);
	}
	
	/**
	 * 將系統當前格式化日期 为 MMdd 的样式
	 * 
	 * @param date
	 * @return
	 */
	public static String getSystemCurrentDateMMdd() {
		return formatDate(Calendar.getInstance().getTime(), DateFormatPattern.DEFAULT_MONTH_PARTITION);
	}
	/**
	 * 將系統當前格式化日期 为 YYYY 的样式
	 * 
	 * @param date
	 * @return
	 */
	public static String getSystemCurrentDateYYYY() {
		return formatDate(Calendar.getInstance().getTime(), DateFormatPattern.DEFAULT_YEAR);
	}
	
	public static String getSystemCurrentDateMM() {
		return formatDate(Calendar.getInstance().getTime(), DateFormatPattern.DEFAULT_MONTH);
	}
	
	public static String getSystemCurrentDateDD() {
		return formatDate(Calendar.getInstance().getTime(), DateFormatPattern.DEFAULT_DD);
	}
	/**
	 * 將系統前一天格式化日期 为 yyyyMMdd 的样式
	 * 
	 * @param date
	 * @return
	 */
	public static String getSystemBeforeNDayDateSimple(Integer n) {
		// 取得前一天的日期
		Calendar calendar = Calendar.getInstance();
		calendar.add(Calendar.DATE, -n);
		return formatDate(calendar.getTime(), DateFormatPattern.DEFAULT_FULL_DATE_NO_PARTITION);
	}
	
	public static String getSystemBeforeNDayDateSimpleTemp(Integer n) {
		// 取得前一天的日期
		Calendar calendar = Calendar.getInstance();
		calendar.add(Calendar.DATE, n);
		return formatDate(calendar.getTime(), DateFormatPattern.DEFAULT_FULL_DATE);
	}
	
	/**
	 * 將系統前N天格式化日期 为 yyyyMMdd 的样式
	 * 
	 * @param date
	 * @return
	 */
	public static String getSystemBeforeDayDateSimple() {
		// 取得前一天的日期
		Calendar calendar = Calendar.getInstance();
		calendar.add(Calendar.DATE, -1);
		return formatDate(calendar.getTime(), DateFormatPattern.DEFAULT_FULL_DATE_NO_PARTITION);
	}
	
	/**
	 * 
     * 格式化日期 为 DateFormatPattern 的样式
     * 
     * @param pattern
     * @param date
     * @return
     */
	public static String formatDate(Date date, DateFormatPattern pattern) {
		if (date != null) {
			return new SimpleDateFormat(pattern.getPattern()).format(date);
	    }
	    else {
	    	return "";
	    }
	}
	
	/**
	 *  将传入的日期转成制定格式的字串
	 * @param date
	 * @param pattern
	 * @return
	 */
	public static String formatDate(Date date , String pattern) {
		if (date != null) {
			return new SimpleDateFormat(pattern).format(date);
		}
		else {
			return "";
		}
	}
	
	/**
	 *  将当前系统日期转成制定格式的字串
	 * @param date
	 * @param pattern
	 * @return
	 */
	public static String formatDate(String pattern) {
		return formatDate(Calendar.getInstance().getTime(), pattern);
	}
	
	/**
	 * 格式化时间 为 hh:mm:ss 的样式
	 * 
	 * @param date
	 * @return
	 */
	public static String formatTime(Date date, String pattern) {

		if (date != null) {
			return new SimpleDateFormat(pattern).format(date);
		}
		else {
			return "";
		}
	}

	/**
	 * 计算 日期 calendar1 与 calendar2 之间的所查的天数 ,注：return calendar1 - calendar2
	 * 
	 * @param calendar1
	 *          日期1
	 * @param calendar2
	 *          日期2
	 * @return 相差天数 = 日期1 - 日期2
	 */
	public static int dateSubtraction(Calendar calendar1, Calendar calendar2) {
		long daterange = calendar1.getTime().getTime()
				- calendar2.getTime().getTime();
		long time = 1000 * 3600 * 24;

		return (int) (daterange / time);
	}
	
	
	/**
	 * 计算 日期 date1 与 date2 之间的所相差的天数 ,
	 * 
	 * @param date1
	 *          日期1
	 * @param date2
	 *          日期2
	 * @return 相差天数 = 日期1 - 日期2
	 */
	public static String dateSubtraction(Date date1, Date date2) {
		if(date1==null||date2==null){
			return "";
		}
		
		Calendar calendar1 = Calendar.getInstance();
		Calendar calendar2 = Calendar.getInstance();
		calendar1.setTime(date1);
		calendar2.setTime(date2);
		return String.valueOf(dateSubtraction(calendar1,calendar2));
		
	}
	
	public static Integer dateSubtractionTemp(Date date1, Date date2) {
		if(date1==null||date2==null){
			return 0;
		}
		
		Calendar calendar1 = Calendar.getInstance();
		Calendar calendar2 = Calendar.getInstance();
		calendar1.setTime(date1);
		calendar2.setTime(date2);
		return dateSubtraction(calendar1,calendar2);		
	}
	
	public static Integer dateSubtractionStr(String dateStr1, String dateStr2) {
		if(dateStr1==null||dateStr2==null){
			return 0;
		}
		Date date1 = new Date();
		Date date2 = new Date();
		try {
			date1 = strToDate(dateStr1);
			date2 = strToDate(dateStr2);
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		Calendar calendar1 = Calendar.getInstance();
		Calendar calendar2 = Calendar.getInstance();
		calendar1.setTime(date1);
		calendar2.setTime(date2);
		return dateSubtraction(calendar1,calendar2);		
	}
	
	/**
	 * 將 yyyy/MM/dd 格式的日期字串，轉成Calendar物件
	 * @param strDate
	 * @return
	 */
	public static Calendar transDate(String strDate){
		if (strDate != null && strDate.length() >= 8){
			Calendar calendar = Calendar.getInstance();
			calendar.setTime(java.sql.Date.valueOf(strDate.replace('/', '-')));
			
			return calendar;
		}
		else{
			return null;
		}
	}
	
	/**
	 * 计算两个日期相差月数
	 * @param calendarDate1
	 * @param calendarDate2
	 * @return
	 */
	public static int computeMonth(Calendar calendarDate1, Calendar calendarDate2) {
		int iMonth = 0;
		int flag = 0;
		try {
			
			logger.debug("calendarDate1:" + calendarDate1.getTime());
			logger.debug("calendarDate2:" + calendarDate2.getTime());
			
			if (calendarDate2.equals(calendarDate1)){
				return 0;
			}
				
			if (calendarDate1.after(calendarDate2)) {
				Calendar temp = calendarDate1;
				calendarDate1 = calendarDate2;
				calendarDate2 = temp;
			}
			
			logger.debug("calendarDate1:" + calendarDate1.getTime());
			logger.debug("calendarDate2:" + calendarDate2.getTime());
			
			if (calendarDate2.get(Calendar.DAY_OF_MONTH) < calendarDate1
					.get(Calendar.DAY_OF_MONTH)){
				flag = 1;
			}
			
			if (calendarDate2.get(Calendar.YEAR) > calendarDate1
					.get(Calendar.YEAR)){
				iMonth = ((calendarDate2.get(Calendar.YEAR) - calendarDate1
						.get(Calendar.YEAR))
						* 12 + calendarDate2.get(Calendar.MONTH) - flag)
						- calendarDate1.get(Calendar.MONTH);
			}
			else{
				iMonth = calendarDate2.get(Calendar.MONTH)
				- calendarDate1.get(Calendar.MONTH) - flag;
			}
		}
		catch (Exception e) {
			logger.error("月份计算处理异常:"+e.getMessage());
		}
		
		return iMonth;
	}
	public static Date strToDate(String strDate) throws ParseException {
	   SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
	   Date strtodate = formatter.parse(strDate);
	   return strtodate;
	}
	
	 /** 通过 yyyy-MM-dd 得到中文大写格式 yyyy MM dd 日期 */
    public static synchronized String toChinese(String str) {
        StringBuffer sb = new StringBuffer();
        sb.append(getSplitDateStr(str, 0)).append("-").append(
                getSplitDateStr(str, 1)).append("-").append(
                getSplitDateStr(str, 2));
        return sb.toString();
    }

    /** 分别得到年月日的大写 默认分割符 "-" */
    public static String getSplitDateStr(String str, int unit) {
        // unit是单位 0=年 1=月 2日
        String[] DateStr = str.split("-");
        if (unit > DateStr.length)
            unit = 0;
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < DateStr[unit].length(); i++) {

            if ((unit == 1 || unit == 2) && Integer.valueOf(DateStr[unit]) > 9) {
                sb.append(convertNum(DateStr[unit].substring(0, 1)))
                        .append("拾").append(
                                convertNum(DateStr[unit].substring(1, 2)));
                break;
            } else {
                sb.append(convertNum(DateStr[unit].substring(i, i + 1)));
            }
        }
        if (unit == 1 || unit == 2) {
            return sb.toString().replaceAll("^壹", "").replace("零", "");
        }
        return sb.toString();

    }

    /** 转换数字为大写 */
    private static String convertNum(String str) {
        return NUMBERS[Integer.valueOf(str)];
    }

    /** 判断是否是零或正整数 */
    public static boolean isNumeric(String str) {
        Pattern pattern = Pattern.compile("[0-9]*");
        Matcher isNum = pattern.matcher(str);
        if (!isNum.matches()) {
            return false;
        }
        return true;
    }

    public static void main(String args[]) {

        System.out.println(toChinese("2008-10-02"));
        String[] str = toChinese("2008-10-02").split("-");
    }
}
